import { Form, Button, Input } from '@nutui/nutui-react-taro';
import Taro from "@tarojs/taro";
import { Api } from '../../api'

const Register = () => {
  const submitFailed = (error: any) => {
    if (error?.length > 0) {
      Taro.showToast({ title: error[0].message, icon: 'error' })  // 提示错误信息
      return
    }
  }

  const submitSucceed = (values: any) => {
    Api.registerApi(values).then((res: any) => {
      console.log('registerApi: ', res)
      if (res.data) {
        Taro.showToast({ title: '注册成功', icon: 'success' })  // 提示注册成功
        Taro.reLaunch({ url: '/pages/login/index' })  // 注册成功后重新跳转到登录页面
      } else {
        Taro.showToast({ title: '注册失败', icon: 'error' })  // 提示注册失败
      }
    })
  }

  const valueRangeValidator = (rule: any, value: string) => {
    // 密码必须是6位数字
    return /^\d{6}$/.test(value)
  }

  return (
    <div className="bg-white h-full w-full pt-10">
      <Form
        className="mt-0px"
        onFinish={(values) => submitSucceed(values)}  // 注册成功时的回调函数
        onFinishFailed={(values, errors) => submitFailed(errors)}  // 注册失败时的回调函数
        footer={
          <div className="w-full flex justify-center">
            <Button formType="submit" type="primary" className="w-3/4">
              注册
            </Button>
          </div>
        }
      >
        <Form.Item
          label="员工编号"
          name="employeeId"
          rules={[{ required: true, message: "请输入员工编号" }]}  // 员工编号为必填项
        >
          <Input placeholder="请输入员工编号" type="text" />
        </Form.Item>

        <Form.Item
          label="用户名"
          name="username"
          rules={[{ required: true, message: "请输入用户名" }]}  // 用户名为必填项
        >
          <Input placeholder="请输入用户名" type="text" />
        </Form.Item>

        <Form.Item
          label="密码"
          name="password"
          rules={[
            { required: true, message: "请输入密码" },  // 密码为必填项
            { validator: valueRangeValidator, message: "密码必须是6位数字" },  // 密码必须是6位数字
          ]}
        >
          <Input placeholder="请输入密码（6位数字）" type="password" />
        </Form.Item>
      </Form>
    </div>
  )
}

export default Register;